#include "mainwindow.h"
#include "context.h"
#include "frame.h"
#include "frame_drive.h"
#include "key_device.h"
#include "qcontainerfwd.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    context = new Context(this);

    connect(context, &Context::OnFrameChangedByRemote, this, [&](const QString &frame) {
        if (frame == "State")
        {
            UpdateFrameState();
        }
    });
    connect(context->js, &JoystickDevice::OnInput, this, &MainWindow::OnJS);
    connect(context->key, &KeyDevice::OnInput, this, &MainWindow::OnKey);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::OnKey(KeyDevice::KeyCode code)
{
    QString str = "detected key: " + QString::number(code);
    ui->label_key->setText(str);
}
void MainWindow::OnJS(QVector<float> values)
{
    QString str = "detected joystick: " + QString::number(values[0]) + ", " + QString::number(values[1]) + ", " +
                  QString::number(values[2]) + ", " + QString::number(values[3]);
    ui->label_js->setText(str);
}

void MainWindow::UpdateFrameState()
{
    // frame=>ui
    ui->label_speed->setText(QString::number(context->frameState->speed * 200) + "km/h");
    ui->label_this_mileage->setText(QString::number(context->frameState->this_mileage) + "km");
}
void MainWindow::SendFrameDrive()
{
    // ui=>frame
    context->frameDrive->gas_pedal_depth = ui->slider_gas_depth->value() / 100.0;
    context->frameDrive->steering_wheel_corners = ui->slider_stering_angle->value() / 100.0;

    // todo...
    context->frameDrive->gear_selection =
        static_cast<FrameDrive::GearSelection>(ui->comboBox_gear_selection->currentIndex());

    context->frameDrive->highBeam = static_cast<FrameDrive::HighBeam>(ui->checkBox_high_beam->isChecked() ? 1 : 0);

    // then frame=>udp=>chassis will be invoke automatically
}
void MainWindow::SendFrameControl()
{
    // ui=>frame

    context->frameDrive->NotifyLocalChange();
    // then frame=>udp=>chassis will be invoke automatically
}
